package Trans_Virtual_Sensor.v1;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Environment;
import android.widget.TextView;

/**
 * 
 * @author ga-youngjoung
 *
 */

public class SenListener implements Runnable, SensorEventListener {
	private static final int SIZE_OF_BUFFER = 10*1024;
	
	private SensorManager mySM;
	private BufferedWriter myBw;
	private Sensor mySensor;
	private int myTypeSensor;
	
	public SenListener(String title, int typeSensor, SensorManager sm) {
		mySM = sm;
		myTypeSensor = typeSensor;
		String nameRoot = Environment.getExternalStorageDirectory().toString();
		//TODO add sensor name
		String namePath = nameRoot + "/" + title + ".csv"; 
    	File outputFile = new File(namePath);
    	OutputStreamWriter osw;
		try {
			osw = new OutputStreamWriter(new FileOutputStream(outputFile));
			myBw = new BufferedWriter(osw, SIZE_OF_BUFFER);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
    	
	}
	
	public void run() {
		synchronized (mySM) {
			List<Sensor> sensorList = mySM.getSensorList(myTypeSensor);
			mySensor = sensorList.get(0);
			mySM.registerListener(this, mySensor, SensorManager.SENSOR_DELAY_FASTEST);
		}
	}
	
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

	public void onSensorChanged(SensorEvent event) {
		if (event.sensor == mySensor) {
			try {
		    	myBw.write(event.timestamp + ",");
		    	for (int i = 0; i < event.values.length; i++) {
		    		myBw.write(event.values[i] + ", ");
		    	}
		    	myBw.newLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	public void pause() {
		try {
			myBw.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void stop() {
		try {
			myBw.flush();
			myBw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		synchronized(mySM) {
			mySM.unregisterListener(this, mySensor);
		}
	}

}
